package com.jetgege.smartbox;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jetgege.smartbox.About.AboutActivity;
import com.jetgege.smartbox.AddBox.AddDeviceActivity;
import com.jetgege.smartbox.Base.BaseActivity;
import com.jetgege.smartbox.BoxSetting.MBoxSettingActivity;
import com.jetgege.smartbox.Guide.UserGuideActivity;
import com.jetgege.smartbox.Tools.Agreement;
import com.jetgege.smartbox.Tools.BluetoothHelper;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jetgege.smartbox.Base.App.connectedDevices;
import static com.jetgege.smartbox.Tools.BluetoothHelper.writeDataBLE;

public class MainActivity extends BaseActivity {

    @BindView(R.id.lv_MenuList)
    ListView lvMenuList;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    MenuAdapter menuAdapter;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    ListView lv_MaskDeviceList;
    DeviceAdapter deviceAdapter;

    List<BluetoothDevice> devices = new ArrayList<>();

    KProgressHUD scanConnect;
    KProgressHUD hudConnect;

    Handler handler;
    final int ACTION_BLE_DEFAULT = 1000;
    final int ACTION_BLE_FOUND = 1001;
    final int ACTION_BLE_DISCOVERY_STARTED = 1002;
    final int ACTION_BLE_DISCOVERY_FINISHED = 1003;
    final int ACTION_BLE_CONNECTED = 1004;
    final int ACTION_BLE_DISCONNECTED = 1005;

    final int DATA_BLE_LEVEL = 2001;//电压等级
    final int DATA_BLE_RUNSTATE = 2002;//运行状态
    final int DATA_BLE_STARTBACK = 2003;//开始运行返回
    final int DATA_BLE_LOWPOWER = 2004;//低电量

    PopupWindow warnTipVindow;
    PopupWindow devicesVindow;
    @BindView(R.id.cb_MainSwitch)
    CheckBox cbMainSwitch;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private void initValue() {
        menuAdapter = new MenuAdapter();
        lvMenuList.setAdapter(menuAdapter);
        toolbar.setTitle("未连接");
        setSupportActionBar(toolbar);
        warnTipVindow = popConnectTip();
        devicesVindow = popDeviceWindow();
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();

        lvMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
//                    case 0:
//                        break;
                    case 0://添加盒子
                        Intent intentStart = new Intent(MainActivity.this, AddDeviceActivity.class);
                        intentStart.setAction("MainActivity");
                        startActivity(intentStart);
                        break;
                    case 1://盒子设置
                        startActivity(new Intent(MainActivity.this, MBoxSettingActivity.class));
                        break;
                    case 2://指导页面
                        startActivity(new Intent(MainActivity.this, UserGuideActivity.class));
                        break;
                    case 3://关于
                        startActivity(new Intent(MainActivity.this, AboutActivity.class));
                        break;
                }
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initValue();
        eventHandle();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (connectedDevices != null)
            toolbar.setTitle(connectedDevices.getName());
        //注册通知
        BluetoothHelper.registerBluetoothBroadcast(MainActivity.this, mReceiver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BluetoothHelper.unRegisterBluetoothBroadcast(MainActivity.this, mReceiver);
    }

    private void eventHandle() {
        //连接要求提示
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (connectedDevices != null) return;//第一次注册就连接了，不需要提示
                if (!warnTipVindow.isShowing()) warnTipVindow.showAsDropDown(toolbar);
            }
        }, 500);

        cbMainSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //开启
                }else {
                    //关闭
                }
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ACTION_BLE_FOUND:
                        if (!devicesVindow.isShowing()) devicesVindow.showAsDropDown(toolbar);
                        deviceAdapter.notifyDataSetChanged();
                        break;
                    case ACTION_BLE_DISCOVERY_STARTED:
                        // pb_Bar.setVisibility(View.VISIBLE);
                        break;
                    case ACTION_BLE_DISCOVERY_FINISHED://扫描结束
                        if (scanConnect == null) return;
                        if (scanConnect.isShowing()) scanConnect.dismiss();
                        // pb_Bar.setVisibility(View.GONE);
                        break;
                    case ACTION_BLE_CONNECTED://连接成功
                        toolbar.setTitle(connectedDevices.getName());
                        devicesVindow.dismiss();
                        hudConnect.dismiss();
                        break;
                    case ACTION_BLE_DISCONNECTED:
                        if (hudConnect != null) hudConnect.dismiss();
                        toolbar.setTitle("未连接");
                        connectedDevices = null;
                        break;
                    case DATA_BLE_STARTBACK:
                        if (msg.arg1 == 255) {
                            writeDataBLE(Agreement.runState);
                        }
                        break;
                    case DATA_BLE_LOWPOWER:
                        lowPowerTip();
                        break;
                    default:
                        break;

                }
            }
        };

    }

    private PopupWindow popDeviceWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        // 引入窗口配置文件
        View view = inflater.inflate(R.layout.popview_device_list, null);
        lv_MaskDeviceList = (ListView) view.findViewById(R.id.lv_MaskDeviceList);

        View headerView = inflater.inflate(R.layout.popview_device_list_headview, null);
        lv_MaskDeviceList.addHeaderView(headerView);

        deviceAdapter = new DeviceAdapter(devices);
        lv_MaskDeviceList.setAdapter(deviceAdapter);

        // 创建PopupWindow对象
        final PopupWindow pop = new PopupWindow(view, DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT, false);
        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BluetoothHelper.stopScan(mLeScanCallback);
            }
        });

        lv_MaskDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) return;
                if (BluetoothHelper.isScaning)
                    BluetoothHelper.stopScan(mLeScanCallback);
                if (BluetoothHelper.isConnected())
                    BluetoothHelper.cancle();
                connectedDevices = devices.get(position - 1);
                hudConnect = KProgressHUD.create(MainActivity.this)
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setLabel("正在连接...")
                        .setCancellable(true)
                        .show();
                BluetoothHelper.conn(connectedDevices, characteristicCallBack);
            }
        });
        return pop;
    }

    private void scanTips() {
        scanConnect = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在搜索设备...")
                .setCancellable(true)
                .show();
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Message msg = handler.obtainMessage();
            if (BluetoothHelper.ACTION_BLE_DISCOVERY_STARTED.equals(action))//开始扫描
                msg.what = ACTION_BLE_DISCOVERY_STARTED;
            else if (BluetoothHelper.ACTION_BLE_DISCOVERY_FINISHED.equals(action))//扫描结束
                msg.what = ACTION_BLE_DISCOVERY_FINISHED;
            else if (BluetoothHelper.ACTION_BLE_CONNECTED.equals(action))//连接成功
            {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        writeDataBLE(Agreement.runState);//状态查询
                    }
                }, 1000);
                msg.what = ACTION_BLE_CONNECTED;
            } else if (BluetoothHelper.ACTION_BLE_DISCONNECTED.equals(action))//断开连接
                msg.what = ACTION_BLE_DISCONNECTED;
            else
                msg.what = ACTION_BLE_DEFAULT;
            handler.sendMessage(msg);
        }
    };


    boolean isLowPwer = false;//低电量纪录
    private BluetoothHelper.CharacteristicCallBack characteristicCallBack = new BluetoothHelper.CharacteristicCallBack() {

        @Override
        public void onCallBack(byte[] data) {
            Message msg = handler.obtainMessage();
            switch (data[0]) {
                case (byte) 0x83://工作电压设置返回
                    msg.what = DATA_BLE_LEVEL;
                    msg.arg1 = data[1] & 255;
                    break;
                case (byte) 0x82://开始运行返回
                    msg.what = DATA_BLE_STARTBACK;
                    msg.arg1 = 255;//255为正常，能返回表示正常
                    break;
                case (byte) 0x81://获取运行状态返回
                    msg.what = DATA_BLE_RUNSTATE;
                    msg.arg1 = data[1];//运行状态
                    //联合运算
                    int dataH = data[3];//)&65280;
                    int dataL = +data[2] & 255;
                    int secondTime = ((dataH << 8) & 65280) + dataL;
                    msg.arg2 = secondTime;
                    Bundle bundle = new Bundle();
                    int num = data[4] & 255;
                    bundle.putInt("Level", num);
                    msg.setData(bundle);
                    break;
                case (byte) 0xff://低电量状态返回
                    if (!isLowPwer) {
                        isLowPwer = true;
                        msg.what = DATA_BLE_LOWPOWER;
                    }
                    break;
            }
            handler.sendMessage(msg);
        }
    };

    /**
     * 扫描回调
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    Message msg = handler.obtainMessage();
                    String deviceName = device.getName();
                    if (deviceName == null) return;
                    if (deviceName.length() < 10) return;
                    String regexChar = (String) deviceName.subSequence(0, 7);
                    if (regexChar.equals("Goockr-")) {
                        if (scanConnect.isShowing()) scanConnect.dismiss();
                        if (!devices.contains(device))
                            devices.add(device);
                        msg.what = ACTION_BLE_FOUND;
                        handler.sendMessage(msg);
                    }
                }
            };

    /**
     * 蓝牙未连接前的提示框
     *
     * @return
     */
    private PopupWindow popConnectTip() {

        LayoutInflater inflater = LayoutInflater.from(this);
        // 引入窗口配置文件
        View view = inflater.inflate(R.layout.popview_unconnect_tips, null);
        // 创建PopupWindow对象
        final PopupWindow pop = new PopupWindow(view, DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT, false);
        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);
        return pop;
    }

    /**
     * 未连接提示
     */
    private boolean tipConnect() {
        if (!BluetoothHelper.isConnected()) {
            TextView tv_Tip = new TextView(this);
            tv_Tip.setText("未使用面膜！");
            tv_Tip.setTextColor(Color.WHITE);
            tv_Tip.setTextSize(18);
            final KProgressHUD hudUNUse = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCustomView(tv_Tip)
                    .setCancellable(true)
                    .setAutoDismiss(true)
                    .show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    hudUNUse.dismiss();
                }
            }, 1000);
            return false;
        }
        return true;
    }

    /**
     * 低电量提示
     */
    private void lowPowerTip() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(this)
                .setMessage("电池电量低，请更换电池！")
                .setCancelable(false)
                .setPositiveButton("知道了",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
        // 显示
        normalDialog.show();
    }


    @Override
    public void onBackPressed() {

        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        startActivity(new Intent(MainActivity.this, UserGuideActivity.class));
        overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        return true;
    }

    @OnClick({R.id.fab, R.id.imageView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fab:
                if (devices.size() > 0) devices.clear();
                scanTips();//搜索提示
                BluetoothHelper.scanLeDevice(mLeScanCallback);
                break;
            case R.id.imageView:
//                startActivity(new Intent(MainActivity.this, MeActivity.class));
//                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
        }
    }


////        Snackbar.make(fab, "Replace with your own action", Snackbar.LENGTH_LONG)
////                .setAction("Action", null).show();


}
